package com.qf;


import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

//66666666666666666666666666666666666667
public class DruidJdbcUtils {
    //benditijiao
    //只要本地
    private static DataSource ds ; //声明数据源
    //创建ThreadLocal线程对象，每个线程有属于自己的连接
    private static ThreadLocal<Connection> tl = new ThreadLocal<>();
    static{
        try {

            Properties prop  = new Properties() ;
            InputStream inputStream = DruidJdbcUtils.class.getClassLoader().getResourceAsStream("druid.properties");
            prop.load(inputStream);
            ds = DruidDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //创建获取数据源的方法
    public static DataSource getDataSource() {
        return ds;
    }

    //创建获取连接的方法
    public static Connection getConnection() throws SQLException {
        //从当前线程获取连接
        Connection conn = tl.get();
        //判断当前线程是否为空
        if(conn == null) {
            //如果为空，则从数据源中获取连接对象
            conn = ds.getConnection();
            //将连接与当前线程绑定
            tl.set(conn);
        }
        //返回当前连接对象
        return conn;
//        return  ds.getConnection() ;
    }

    //创建关闭连接的方法
    public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public void close(PreparedStatement ps, Connection conn) {
        if(ps != null) {
            try {
                ps.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection conn=getConnection();
        System.out.println(conn);
    }


}
